package com.gao.api.gate.quick.tt;

import io.netty.channel.pool.AbstractChannelPoolMap;
import io.netty.channel.pool.ChannelPoolMap;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * <p></p>
 *
 * @author gaoshuangwen
 * @since 2022/02/14 20:39
 */
public abstract class ChannelPoolManager<K> extends AbstractChannelPoolMap<K, IdleChannelPool> implements ChannelPoolMap<K, IdleChannelPool> {

    private final int maxChannelPoolTtl;
    private final int maxChannelPoolIdleTime;
    private final long period;
    private Runnable evictTask =() -> forEach(pool -> {
        IdleChannelPool value = pool.getValue();
        if (value.isExpired()) {
            remove(pool.getKey());
        }
    });
    private final ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);

    public ChannelPoolManager(int maxChannelPoolTtl, int maxChannelPoolIdleTime,int period) {
        this.maxChannelPoolTtl = maxChannelPoolTtl;
        this.maxChannelPoolIdleTime = maxChannelPoolIdleTime;
        this.period = period;
        executor.scheduleAtFixedRate(
                evictTask,
                0,
                period,
                TimeUnit.MILLISECONDS);
    }
    protected IdleChannelPool newPool(K key){
        return newIdlePool(key,maxChannelPoolTtl,maxChannelPoolIdleTime);
    }

    protected abstract IdleChannelPool newIdlePool(K key, int maxChannelPoolTtl, int maxChannelPoolIdleTime);

}
